package  net.assassin.rss.services
{
	import flash.net.URLVariables;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	/**
	 *  2011-4-7  petersx.g@gmail.com
	 * 
	 * 	e.g. :http://news.google.com/news?ned=cn&output=rss&topic=b
	 */
	public class DefaultRSSLoadByHTTPSerivce implements IRSSLoadService
	{
		private static var instance:DefaultRSSLoadByHTTPSerivce;
		private var rpcAdapter:HTTPService;
		
		public function DefaultRSSLoadByHTTPSerivce()
		{
			if(instance){
				throw new Error("");
			}
			rpcAdapter = new HTTPService();
			rpcAdapter.addEventListener(ResultEvent.RESULT, resultHandler);
			rpcAdapter.addEventListener(FaultEvent.FAULT, faultHandler);
		}
		protected function resultHandler(result:ResultEvent):void{
			try{
				//var xml:XML = new XML(result.token.result);
				if(result.token.successFn != null && result.token.successFn is Function){
					(result.token.successFn as Function).apply(null,[result]);
				}
			}catch(err:Error){
				
			}
			
		}
		
		protected function faultHandler(fault:FaultEvent):void{
			//TODO error
		}
		public static function getInstance():DefaultRSSLoadByHTTPSerivce{
			if(!instance){
				instance = new DefaultRSSLoadByHTTPSerivce();
			}
			return instance;
		}
		
		public function load(feed:String, params:URLVariables=null,method:String="GET", infoObject:Object=null, successFn:Function=null, faultFn:Function=null):AsyncToken
		{
			rpcAdapter.url = feed;
			rpcAdapter.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
			rpcAdapter.method = method;
			var token:AsyncToken = rpcAdapter.send(params);
			
			token["feed"] = feed;
			token["successFn"] = successFn;
			token["faultFn"] = faultFn;
			token["infoObject"] = infoObject;
			return token;
		}
	}
}